package com.zhuoya.healthcard;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.epson.isv.eprinterdriver.Common.EpsStatus;
import com.epson.isv.eprinterdriver.Ctrl.EPSetting;
import com.epson.isv.eprinterdriver.Ctrl.EPrintManager;
import com.epson.isv.eprinterdriver.Ctrl.IPrintListener;
import com.zhuoya.healthcard.contants.Contants;
import com.zhuoya.healthcard.util.EPLog;
import com.zhuoya.healthcard.util.HttpUtil;
import com.ldoublem.loadingviewlib.view.LVCircularZoom;

import static com.epson.isv.eprinterdriver.Common.ServiceIntent.QueryFinishFactor.UserCancel;
import static com.epson.isv.eprinterdriver.Common.ServiceIntent.StopFactor.PrintSuccess;
import static com.epson.isv.eprinterdriver.Common.ServiceIntent.StopFactor.PrinterErrorOccur;
import static com.epson.isv.eprinterdriver.Common.ServiceIntent.StopFactor.PrinterStopButton;

public class PrintListenerActivity extends BaseActity implements IPrintListener {
    public static final int MSG_UPDATE_TEXT = 0;
    public static final int OP_HEAD_CLEANING = 3;
    public static final int OP_NOZZLE_CHECK = 2;
    public static final int OP_PAPER_FEED = 4;
    public static final int OP_PRINT = 1;
    public static final int OP_ZERO = 0;
    private static final String TAG = "PrintListenerActiviity";
    String imagePath;
    ImageView imageView;
    LVCircularZoom mLoading;
    private TextView mTimeCount;
    int opCode;
    String registrationId;
    TextView tvPntStatus;
    boolean lastCancel;
    private CountDownTimer countDownTimer;


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer!=null){
            countDownTimer.cancel();
        }
        handler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onCreate(final Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_print);
        initView();
        EPrintManager.instance().addPrintListener(this);
        final Intent intent = this.getIntent();
        final int intExtra = intent.getIntExtra("opCode", 0);
        this.registrationId = intent.getStringExtra("registrationId");
        if (intExtra == 0) {
            return;
        }
        this.opCode = intExtra;
        final int opCode = this.opCode;
        if (opCode == 1) {
            EPLog.v("PrintListenerActiviity", "onCreate() OP_PRINT");
            final String stringExtra = intent.getStringExtra("imgUrl");
            if (stringExtra != null) {
                final StringBuilder sb = new StringBuilder();
                sb.append("onCreate() OP_PRINT imagePath =");
                sb.append(stringExtra);
                EPLog.d("PrintListenerActivity", sb.toString());
                this.imagePath = stringExtra;
            }
            EpsStatus status = EPrintManager.instance().getStatus();
            if (status.getPrinterStatus()==EpsStatus.PrinterStatus.EPS_PRNST_BUSY||status.getPrinterStatus()==EpsStatus.PrinterStatus.EPS_PRNST_PRINTING
                    ||status.getPrinterStatus()==EpsStatus.PrinterStatus.EPS_PRNST_CANCELLING) {
                lastCancel=true;
                tvPntStatus.setText("打印机忙碌中，请稍后");
                loopPrintStatus();

            }else {
                lastCancel=false;
                EPrintManager.instance().startPrint();
            }



            return;
        }
        if (opCode == 2) {
            EPLog.v("PrintListenerActiviity", "onCreate() OP_NOZZLE_CHECK");
            EPrintManager.instance().startNozzleCheck();
            return;
        }
        if (opCode == 3) {
            EPLog.v("PrintListenerActiviity", "onCreate() OP_HEAD_CLEANING");
            EPrintManager.instance().startHeadCleaning();
            return;
        }
        if (opCode != 4) {
            return;
        }
        EPLog.v("PrintListenerActiviity", "onCreate() OP_PAPER_FEED");
        EPrintManager.instance().startPaperFeed();
    }

    private void initView() {
        this.tvPntStatus = this.findViewById(R.id.textView15);
        this.mLoading = this.findViewById(R.id.loading);
        this.imageView = this.findViewById(R.id.imageView8);
        this.mLoading.setVisibility(View.VISIBLE);
        this.mLoading.startAnim();
        this.mTimeCount = this.findViewById(R.id.timeCount);
        this.findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View view) {
                onBackPressed();
            }
        });
        this.findViewById(R.id.backTV).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View view) {
                onBackPressed();
            }
        });
    }



    @Override
    public void onCleaningTime(final int n) {
        final StringBuilder sb = new StringBuilder();
        sb.append("onCleaningTimeInformation = ");
        sb.append(n);
        sb.append(" seconds");
        this.tvPntStatus.setText((CharSequence) sb.toString());
    }





    @Override
    public String onPageBegin(final int n) {
        final StringBuilder sb = new StringBuilder();
        sb.append("onPageBegin : ");
        sb.append(n);
        sb.append(" : imagePath = ");
        sb.append(this.imagePath);
        EPLog.d("IPrintListener", sb.toString());
        return this.imagePath;
    }

    @Override
    public boolean onPageFinished(final int n) {
        final StringBuilder sb = new StringBuilder();
        sb.append("onPageFinished : ");
        sb.append(n);
        EPLog.d("IPrintListener", sb.toString());
        return n <= EPSetting.instance().getTotalPages();
    }

    @Override
    public void onPrintAutoContinue() {
        EPLog.d("IPrintListener", "onPrintResume");
    }

    @Override
    public void onPrintBegin() {
        EPLog.d("IPrintListener", "onPrintBegin");
        tvPntStatus.setText(getString(R.string.print_status_msg_pntret_printing));


    }

    @Override
    public void onPrintFinished(int factor) {
        final StringBuilder sb = new StringBuilder();
        sb.append("onPrintFinished : ");
        sb.append(factor);
        EPLog.d("IPrintListener", sb.toString());
        this.mLoading.setVisibility(View.INVISIBLE);

        int msg;
        switch (factor) {
            case PrintSuccess:
                this.imageView.setImageBitmap(BitmapFactory.decodeResource(this.getResources(), R.drawable.success));
                msg = R.string.print_status_msg_pntret_success;
                if(!lastCancel){
                     countDownTimer=new CountDownTimer(1000,3000) {
                        @Override
                        public void onTick(long millisUntilFinished) {
                            tvPntStatus.setText((millisUntilFinished/1000)+"秒后自动返回首页");
                        }

                        @Override
                        public void onFinish() {
                            onBackPressed();
                        }
                    };
                    countDownTimer.start();

                }
                break;


            case PrinterStopButton:
                msg = R.string.print_status_msg_pntret_stopbutton;
                break;

            case UserCancel:
                msg = R.string.print_status_msg_pntret_usercancel;
                break;

            case PrinterErrorOccur:
                msg = R.string.print_status_msg_pntret_printererror;
                break;

            default: {
                msg = R.string.print_status_msg_pntret_printererror;
                break;
            }
        }
        if (factor != PrintSuccess) {
            this.imageView.setImageBitmap(BitmapFactory.decodeResource(this.getResources(), R.drawable.print_error));
            new Thread(new Runnable() {
                @Override
                public void run() {
                    final JSONObject jsonObject = new JSONObject();
                    jsonObject.put("registrationId", registrationId);
                    HttpUtil.submitPostData(Contants.uri + "order/registrationRecall", jsonObject, "utf-8");
                }
            }).start();
        }
        tvPntStatus.setText(msg);

    }

    @Override
    public void onPrintPause(final int n, final int n2, final EpsStatus epsStatus) {
        final StringBuilder sb = new StringBuilder();
        sb.append("onPrintPause : ");
        sb.append(n);
        sb.append(" pauseFactor : ");
        sb.append(n2);
        sb.append(" isJobContinue : ");
        sb.append(epsStatus.isJobContinue());
        EPLog.d("IPrintListener", sb.toString());
        this.tvPntStatus.setText((CharSequence) "\u6253\u5370\u673a\u7f3a\u7eb8");
        new Thread(new Runnable() {
            @Override
            public void run() {
                final JSONObject jsonObject = new JSONObject();
                jsonObject.put("registrationId", registrationId);
                HttpUtil.submitPostData(Contants.uri + "order/registrationRecall", jsonObject, "utf-8");
            }
        }).start();
    }

    @Override
    public void onPrintResume() {
        EPLog.d("IPrintListener", "onPrintResume");
    }


    @Override
    public void onBackPressed() {
        EpsStatus status = EPrintManager.instance().getStatus();
        if (status.getPrinterStatus()==EpsStatus.PrinterStatus.EPS_PRNST_BUSY||status.getPrinterStatus()==EpsStatus.PrinterStatus.EPS_PRNST_PRINTING
                ||status.getPrinterStatus()==EpsStatus.PrinterStatus.EPS_PRNST_CANCELLING) {
        }else {
            tvPntStatus.setText(getString(R.string.print_status_msg_canceling));
            EPrintManager.instance().cancelPrint();
        }

        startActivity(new Intent(this, MainActivity.class));
    }

    Handler handler=new Handler();
    Runnable runnable=new Runnable() {
        @Override
        public void run() {
            if (EPrintManager.instance().getStatus().getPrinterStatus()!=EpsStatus.PrinterStatus.EPS_PRNST_IDLE){
                handler.postDelayed(this,1000);
            }else {
                lastCancel=false;
                EPrintManager.instance().cancelPrint();
                EPrintManager.instance().startPrint();
            }

        }
    };

    private void loopPrintStatus(){
        handler.postDelayed(runnable,1000);

    }



}
